package com.jjc.android.util

import android.text.Html
import android.text.TextUtils
import android.widget.TextView
import androidx.core.text.HtmlCompat
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.floor

object Common {
    var sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    var yymmdd = SimpleDateFormat("yyyy/MM/dd", Locale.getDefault())
    var yymmdd2 = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    fun parseFormat(date:String?,paramFormat: SimpleDateFormat,targetFormat: SimpleDateFormat):String{
        if(date.isNullOrEmpty()) return ""
        return try {
            paramFormat.parse(date)?.let {
                targetFormat.format(it)
            }
        }catch (e:Exception){
            null
        }.let {
            if(it.isNullOrEmpty()) date else it
        }
    }

    fun parseFormat(date:String?,paramFormat: SimpleDateFormat):Calendar?{
        if(date.isNullOrEmpty()) return null
        return try {
            paramFormat.parse(date)?.let {date->
                Calendar.getInstance().also {
                    it.time = date
                }
            }
        }catch (e:Exception){
            null
        }
    }

    fun TextView.formatHtml(value:String?){
        if(value.isNullOrEmpty()){
            setText("")
        }else{
            setText( HtmlCompat
                .fromHtml(value, HtmlCompat.FROM_HTML_MODE_COMPACT, null, HtmlTagHandler(HtmlTagUtil.NEW_SPAN, context)))
        }
    }

    fun Int.parseTwo():String{
        return if(this<=9) "0${this}" else this.toString()
    }

    fun String?.parseEmpty(empty:String = ""):String{
        return if(this.isNullOrEmpty()) empty else this
    }

    fun String?.parseInt():Int{
        return try {
            floor(parseFloat().toDouble()).toInt()
        }catch (e:Exception){
            0
        }
    }
    fun String?.parseLong():Long{
        return try {
            this?.toDouble()?.toLong()?:0L
        }catch (e:Exception){
            0L
        }
    }

    fun String?.parseFloat():Float{
        return try {
            this?.toFloat() ?:0f
        }catch (e:Exception){
            0f
        }
    }

    fun getAge(birthDay: String?): Int {
        return try {
            getAge(yymmdd2.parse(birthDay))
        } catch (e: java.lang.Exception) {
            0
        }
    }

    fun getAge(birthDay: Date?): Int {
        val cal = Calendar.getInstance()
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            return 0
        }
        val yearNow = cal[Calendar.YEAR] //当前年份
        val monthNow = cal[Calendar.MONTH] //当前月份
        val dayOfMonthNow = cal[Calendar.DAY_OF_MONTH] //当前日期
        cal.time = birthDay
        val yearBirth = cal[Calendar.YEAR]
        val monthBirth = cal[Calendar.MONTH]
        val dayOfMonthBirth = cal[Calendar.DAY_OF_MONTH]
        var age = yearNow - yearBirth //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age-- //当前日期在生日之前，年龄减一
            } else {
                age-- //当前月份在生日之前，年龄减一
            }
        }
        return age
    }

    private val decimal_format_1dp = DecimalFormat("#.#")
    @JvmStatic
    fun getExposureTimeString(exposure_time: Long): String {
        /*if( MyDebug.LOG )
            Log.d(TAG, "getExposureTimeString(): " + exposure_time);*/
        val exposure_time_s = exposure_time / 1000000000.0
        val string: String
        string = if (exposure_time > 100000000) {
            // show exposure times of more than 0.1s directly
            decimal_format_1dp.format(exposure_time_s) + "s"
        } else {
            val exposure_time_r = 1.0 / exposure_time_s
            " 1/" + (exposure_time_r + 0.5).toInt() + "s"
        }
        /*if( MyDebug.LOG )
            Log.d(TAG, "getExposureTimeString() return: " + string);*/return string
    }


    //判断闰年
    private fun isLeap(year: Int): Boolean {
        return year % 100 == 0 && year % 400 == 0 || year % 100 != 0 && year % 4 == 0
    }

    fun getDays(year: Int, month: Int): Int {
        val days: Int
        var FebDay = 28
        if (isLeap(year)) FebDay = 29
        days = when (month) {
            1, 3, 5, 7, 8, 10, 12 -> 31
            4, 6, 9, 11 -> 30
            2 -> FebDay
            else -> 0
        }
        return days
    }

    fun settingphone(str: String?): String {
        if(str.isNullOrEmpty()) return ""
        return if (TextUtils.isEmpty(str)) str else str.replace(
            "(\\d{3})\\d{4}(\\d{4})".toRegex(),
            "$1****$2"
        )
    }

}